package cn.itcast.n4_共享模型_管程;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * Test46_$$$$$_设计模式之顺序控制_wait_notify实现先打印1再打印2
 * </p>
 *
 * @author flyduck
 * @since 2024-11-01
 */
@Slf4j(topic = "c.Test46_$$$$$_设计模式之顺序控制_wait_notify实现先打印2再打印1")
public class Test46_$$$$$_设计模式之顺序控制_wait_notify实现先打印2再打印1 {

    static final Object lock = new Object();
    static boolean twoPrinted = false;//2是否已经打印过

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (lock) {
                while (!twoPrinted){//没有运行过，等待
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("1");
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            synchronized (lock) {
                log.debug("2");
                twoPrinted = true;
                lock.notifyAll();
            }

        }, "t2");
        t1.start();
        t2.start();
    }
}
